import eventBus from "@/eventBus";
import defaultGif from "@/assets/default.gif";

let imgs = [];
import {debounce} from "@/utils";
// 调用这个函数就可以设置合适的图片
function setImage(img) {
  img.dom.src = defaultGif;  //默认使用图片
  // 处理图片
  const clientHeight = document.documentElement.clientHeight;
  const rect = img.dom.getBoundingClientRect();
  const height = rect.height || 100;
  if(rect.top >= -height && rect.top <= clientHeight) {
    const tempImg = new Image();
    tempImg.onload = function () {
      img.dom.src = img.src;
    };
    tempImg.src = img.src;
    imgs = imgs.filter(i => i !== img);
  }
}
function setImages() {
  for (const img of imgs) {
    // 处理图片
    setImage(img);
  }
}
function handleScroll(dom) {
  setImages();
}
eventBus.$on("mainScroll", debounce(handleScroll, 50))
export default {
  inserted(el, bindings) {
    const img = {
      dom: el,
      src: bindings.value,
    };
    imgs.push(img);
    // 立即处理
    setImages(imgs);
  },
  unbind(el) {
    imgs = imgs.filter(img => img.dom !== el)
  }
}